package com.docker.fy.service.impl;

import com.docker.common.core.domain.AjaxResult;
import com.docker.fy.mapper.FyDockerDrugMapper;
import com.docker.fy.mapper.FyPatientMapper;
import com.docker.fy.mapper.FyVipMapper;
import com.docker.fy.service.ShoppingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.naming.directory.SearchResult;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 23118
 * @version 1.0
 * @description: TODO
 * @date 2025/4/15 8:55
 */
@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Autowired
    private FyPatientMapper patientMapper;
    @Autowired
    private FyDockerDrugMapper dockerDrugMapper;
    @Autowired
    private FyVipMapper vipMapper;
    @Override
    @Transactional
    public AjaxResult savePrescription(Map map) {
//        System.out.println(map);
        //先根据患者id获取患者信息判断是否是会员
        Map patient = (Map) map.get("patientInfo");
//        System.out.println(patient);
        //患者id
        int patientId = Integer.parseInt(patient.get("cardNumber").toString());
//        System.out.println(patientId);
        //1根据患者id查询患者信息
        Map patientInfo = patientMapper.selectPatientInfoById(patientId);
        System.out.println(patientInfo);
        if (patientInfo == null) {
            //向患者表里面添加患者信息，并返回患者信息
//            int newPatientId = addPatient(patient);
////            System.out.println(newPatientId);
//            //将患者id添加到map中
//            patient.put("cardNumber",newPatientId);
            //现在不在添加患者，直接抛出异常
            throw new RuntimeException("患者信息不存在，请先去办卡");
        }else{
            //判断是否是会员
//            System.out.println(patientInfo.get("") == null );
//            System.out.println(patientInfo.get("vip_grade").equals(0));
            if (patientInfo.get("vipType") == null || patientInfo.get("vipType").equals(0)){
                //不是会员,不打折
            }else{
                //是会员,打折
                double originalAmount = Double.parseDouble(map.get("totalAmount").toString()) * 0.95;
                //保留两位小数
                originalAmount = (double) Math.round(originalAmount * 100) / 100;
                map.put("totalAmount", originalAmount);
            }
        }
        //3库存变动
        updateMedicineStock(map);

        //4向订单表里面添加订单信息
//        System.out.println(map);
//        addOrder(map);
        //5积分变动
        updateScore(map);
        //返回总价结果
        return AjaxResult.success(map.get("totalAmount"));
    }

    //积分变动
    private void updateScore(Map map) {
        //积分map
        Map integralMap = new HashMap();
        //患者信息
        Map patient = (Map) map.get("patientInfo");
//        System.out.println(patient);
        //患者id
        int patientId = Integer.parseInt(patient.get("cardNumber").toString());
        integralMap.put("patient_id",patientId);
        //费用
        double totalAmount = Double.parseDouble(map.get("totalAmount").toString());
        //先跟据患者id查询积分
        Map integral = vipMapper.selectIntegral(patientId);
        //没有数据提醒余额不足，有数据就更新
//        System.out.println(Double.parseDouble(integral.get("balance").toString()) < Double.parseDouble(map.get("MyEndTotalAmount").toString()));
        if (integral == null || Double.parseDouble(integral.get("balance").toString()) < totalAmount){
            //新增
            //保存积分
//            doctorPatientMapper.addIntegral(integralMap);
//            vipMapper.addIntegral(integralMap);
//            return AjaxResult.error("余额不足请去充值");
            throw new RuntimeException("余额不足请去充值");
        }else{
            //余额减少
            double balance = Double.parseDouble(integral.get("balance").toString()) - totalAmount;
//            System.out.println(Double.parseDouble(integral.get("balance").toString()));
//            System.out.println(Double.parseDouble(integralMap.get("points").toString()));
//            System.out.println("balance:" + balance);
            integralMap.put("balance",balance);
            //更新积分double类型
//            System.out.println(integral.get("points").toString());
//            System.out.println(integralMap.get("points").toString());
            double points = Double.parseDouble(integral.get("points").toString()) + totalAmount;
            integralMap.put("points",points);
            //增加累计消费
            double consumption = Double.parseDouble(integral.get("consumption").toString()) + totalAmount;
            integralMap.put("consumption",consumption);

            //如果积分大于1000，就升为会员
            if (points >= 1000){
                integralMap.put("vip_grade",1);
            }else{
                integralMap.put("vip_grade",0);
            }
            System.out.println(integralMap);
            //更新积分
//            doctorPatientMapper.updateIntegral(integralMap);
            vipMapper.updateIntegral(integralMap);
//            System.out.println(1111);
            //跟新患者表数据
            Map patientMap = new HashMap();
            patientMap.put("id",patientId);
            patientMap.put("vipType",integralMap.get("vip_grade"));
            patientMapper.updatePatient(patientMap);
        }
    }

    //库存变动
    private AjaxResult updateMedicineStock(Map map) {
        //药品数据
        List<Map> medicineList = (List<Map>) map.get("medicines");
        //循环遍历药品数据
        for (Map medicine : medicineList) {
            //药品id
            int medicineId = Integer.parseInt(medicine.get("id").toString());
            //药品数量
            int medicineNum = Integer.parseInt(medicine.get("quantity").toString());
            //根据药品id查询药品库存
            int stock = dockerDrugMapper.selectMedicineStockById(medicineId);
            //如果库存大于出库数量
            if (stock >= medicineNum) {
                //库存减去出库数量
                stock -= medicineNum;
                //调用方法去更新药品表
                dockerDrugMapper.updateMedicineStockById(medicineId, stock);
            }else{
                //库存小于出库数量
//                return AjaxResult.error("库存不足");
                throw new RuntimeException("库存不足");
            }
        }
        return AjaxResult.success();
    }

    //添加订单信息
    private void addOrder(Map map) {
        //TODO 需要药品零售和药品的中间表
    }
    //添加患者信息
    private int addPatient(Map patient) {
        Map newPatient = new HashMap<>();
        newPatient.put("name",patient.get("name"));
        newPatient.put("sex",patient.get("gender"));
        newPatient.put("age",patient.get("age"));
        newPatient.put("birthDate",patient.get("birthday"));
        newPatient.put("phone",patient.get("phone"));
        newPatient.put("idNumber",patient.get("idCard"));
        newPatient.put("vipType",0);
        newPatient.put("del",0);
        patientMapper.insertPatientInfo(newPatient);
        //获取患者id
        // 安全获取ID
        Object idObj = newPatient.get("id");
        int newPatientId;

        if (idObj instanceof BigInteger) {
            newPatientId = ((BigInteger) idObj).intValue();
        } else if (idObj instanceof Number) {
            newPatientId = ((Number) idObj).intValue();
        } else {
            try {
                newPatientId = Integer.parseInt(idObj.toString());
            } catch (NumberFormatException e) {
                throw new IllegalStateException("无效的患者ID格式: " + idObj);
            }
        }
        return newPatientId;
    }
}
